package red.stu.mc.mod.codeblock.util;

import java.util.HashMap;
import java.util.List;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

import net.minecraft.client.Minecraft;
import net.minecraft.util.text.TextComponentString;

public class CodeBlockScriptEngineManager {

	// 脚本引擎工厂
	private static ScriptEngineManager scriptEngineManager;

	static {
		try {
			scriptEngineManager = new ScriptEngineManager(null);
			init();
		} catch (Exception e) {
			System.out.println("\nScriptEngineManager Exception:" + e.getMessage());
		}
	}

	private static void init() {
		List<ScriptEngineFactory> list = scriptEngineManager.getEngineFactories();
		for (ScriptEngineFactory f : list) {
			System.out.println("ScriptEngineManager: " + f.getEngineName() + " - " + f.getEngineVersion());
		}
		ScriptEngine scriptEngine = null;
		for (int i = 1; i <= 3; i++) {
			String engineByName = null;
			switch (i) {
			case 1:
				engineByName = "nashorn";
				break;
			case 2:
				engineByName = "js";
			}
			scriptEngine = scriptEngineManager.getEngineByName(engineByName);
			if (scriptEngine != null) {
				System.out.println("USE ScriptEngine > " + engineByName);
				break;
			}
		}
		if (scriptEngine == null)
			System.out.println("BUG: Unable to find the engine!");
	}

	// CodeBlock的组类型初始代码
	public static final String CODEMOD_SCRIPT_INIT = "var System = Java.type('java.lang.System');";
	public static final String CODEMOD_SCRIPT_GROUP_INIT = "CodeVar = JSON.parse(CodeVar);";
	// 每个CodeBlock方块会执行的清理代码
	public static final String CODEMOD_SCRIPT_CLEAR = "var __BackCodeVar = JSON.stringify(CodeVar);";

	private HashMap<String, ScriptEngine> engines = new HashMap<>();

	/**
	 * 获取全新CodeBlock脚本引擎
	 * 
	 * @return
	 */
	public ScriptEngine getNewScriptEngine() {
		ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn");
		if (scriptEngine == null)
			throw new RuntimeException("DBUG: get ScriptEngine is null.");
		// init ScriptEngine Code
		try {
			scriptEngine.eval(CodeBlockScriptEngineManager.CODEMOD_SCRIPT_INIT);
		} catch (Exception e) {
			throw new RuntimeException("DBUG: " + e.getMessage());
		}
		return scriptEngine;
	}

	/**
	 * 获取指定群组的CodeBlock脚本引擎
	 * 
	 * @param groupName
	 *            群组名
	 * @return
	 */
	public synchronized ScriptEngine getScriptEngine(String groupName) {
		ScriptEngine scriptEngine = engines.get(groupName);
		if (scriptEngine == null) {
			scriptEngine = this.getNewScriptEngine();
			engines.put(groupName, scriptEngine);
		}
		return scriptEngine;
	}

	/**
	 * 删除群组缓存的脚本引擎
	 * 
	 * @param groupName
	 * @return
	 */
	public synchronized ScriptEngine removeScriptEngine(String groupName) {
		return engines.remove(groupName);
	}

}
